#include "proxy.h"
#include <iostream>
Proxy::Proxy():mrealSubject(nullptr)
{

}
Proxy::~Proxy()
{

}
std::string Proxy::request(const std::string& data){
    std::cout << "Proxy Handing request " << data << std::endl;
    // 先检查缓存
    std::lock_guard<std::mutex> lock(mtx);
    if(mcache.count(data)){
        std::cout << "Proxy: Returning cached result for: " << data << std::endl;
         std::lock_guard<std::mutex> unlock(mtx);
        return "Proxy: Cached result: " + mcache[data];
    }

    // 如果缓存中不存在，则调用真实主题处理请求
    if (!mrealSubject) {
        mrealSubject = std::make_shared<RealSubject>();
    }
    std::string result = mrealSubject->request(data);

    // 将结果存入缓存
    {
        std::lock_guard<std::mutex> lock(mtx);
        mcache[data] = result;
    }
    std::lock_guard<std::mutex> unlock(mtx);
    return "Proxy: Processed data: " + result;
}
